package com.charlotte.study.gupao.interpreter.calculate.v1;

import java.util.Stack;

/**
 * @author junjie.ding
 * @date 2020/3/23
 */
public class Calculator {

    // 栈
    private Stack<IArithmeticInterpreter> STACK = new Stack<>();


    public Calculator(String expression) {
        this.parse(expression);
    }

    private void parse(String expression) {
        // 默认使用空格进行分割
        String[] elements = expression.split(" ");
        IArithmeticInterpreter left, right;

        for (int i = 0; i < elements.length; i++) {
            String element = elements[i];
            // 判断当前字符串是否为操作符
            if(OperatorUtil.isOperator(element)){
                // 如果当前是操作符，则先从栈里取出一个数据，
                left = this.STACK.pop();
                System.out.println("出栈：" + left.interpret());
                right = new NumberArithmeticInterpreter(Integer.valueOf(elements[++i]));
                Interpreter interpreter = OperatorUtil.getInterpreter(left, right, element);
                this.STACK.push(interpreter);
                System.out.println("入栈：" + interpreter.interpret());
            }else{
                left = new NumberArithmeticInterpreter(Integer.valueOf(element));
                this.STACK.push(left);
                System.out.println("入栈：" + element);
            }
        }
    }

    public int calculate(){
        return this.STACK.pop().interpret();
    }
}
